import { Command } from '../entity/command';
import { DomService } from '@farris/designer-services';
import { Injectable } from '@angular/core';

@Injectable()
export class WebCmdHandlerManager {

  constructor(private domService: DomService) { }

  addCommand(command: Command, handlerCode: string) {
    const webCmds = this.domService.getWebCmds();
    if (webCmds instanceof Array) {
      const webcmd = webCmds.find(item => item.id === command.cmpId);
      if (webcmd) {
        webcmd.refedHandlers = webcmd.refedHandlers || [];
        webcmd.refedHandlers.push({ host: command.id, handler: handlerCode });
      }
    }
  }

  removeCommand(command: Command) {
    const webCmds = this.domService.getWebCmds();
    if (webCmds instanceof Array) {
      const webcmdIndex = webCmds.findIndex(item => item.id === command.cmpId);
      if (webcmdIndex > -1) {
        const webcmd = webCmds[webcmdIndex];
        const handlers = webcmd.refedHandlers;
        const index = handlers.findIndex(item => item.host === command.id);
        handlers.splice(index, 1);
        if (handlers.length === 0) {
          webCmds.splice(webcmdIndex, 1);
        }
      }
    }
  }
}
